<template>
    <div class="inventory-container">
        <div class="left">
            <!-- <nav class="title">能力所属分类</nav> -->
            <div class="content">
                <el-input
                        placeholder="请输入名称搜索"
                        v-model="searchCateName"
                        class="input-with-select"
                        @change="getClassifyList"
                >
                    <el-button
                            slot="append"
                            icon="el-icon-search"
                            :autofocus="true"
                            @click="getClassifyList"
                    ></el-button>
                </el-input>
                <div class="conetnt-box">
                    <el-tree
                            ref="cateTreeRef"
                            :data="classifyList"
                            node-key="cateId"
                            highlight-current
                            check-on-click-node
                            default-expand-all
                            :props="{ label: 'cateName' }"
                            :expand-on-click-node="false"
                            @node-click="handleCateChange"
                    ></el-tree>
                </div>
            </div>
        </div>
        <div class="right">
            <el-form
                    v-show="showSearch"
                    :model="queryParams"
                    ref="queryForm"
                    :inline="true"
                    label-width="70px"
            >
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="能力编码" prop="serviceCodeLike">
                            <el-input
                                    v-model="queryParams.serviceCodeLike"
                                    placeholder="请输入能力编码"
                                    clearable

                                    style="width: 240px"
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="能力名称" prop="serviceNameLike">
                            <el-input
                                    v-model="queryParams.serviceNameLike"
                                    placeholder="请输入能力名称"
                                    clearable

                                    style="width: 240px"
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="能力类型" prop="serviceType">
                            <dict-selector
                                    v-model="queryParams.serviceType"
                                    :dictData="protocolTypeList"
                                    placeholder="请选择能力类型"
                                    clearable
                                    style="width: 240px"

                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="能力方式" prop="serverReleaseType">
                            <el-select
                                    v-model="queryParams.serverReleaseType"
                                    placeholder="请选择能力方式"
                                    style="width: 240px"

                                    clearable
                            >
                                <el-option
                                        v-for="item in releaseTypeArr"
                                        :key="item.key"
                                        :label="item.title"
                                        :value="item.key"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="请求路径" prop="mockUrlLike">
                            <el-input
                                    v-model="queryParams.mockUrlLike"
                                    placeholder="请输入请求路径"
                                    clearable

                                    style="width: 240px"
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="能力状态" prop="serviceStatus">
                            <el-select
                                    v-model="queryParams.serviceStatus"
                                    placeholder="请选择能力状态"
                                    style="width: 240px"

                                    clearable
                            >
                                <el-option
                                        v-for="item in statusOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item>
                            <search-button @click="handleQuery"/>
                            <reset-button @click="resetQuery"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!--            <div  :gutter="10" class="mb8">-->
            <!--                &lt;!&ndash;-->
            <!--                <detail-button @click="handleAction('notFindRoute',{})" text="未加载路由"/>-->
            <!--                &ndash;&gt;-->
            <!--            </div>-->
            <el-row :gutter="10" class="mb8">
                <el-col :span="12">
                    <add-button @click="handleAdd"/>
                    <add-button @click="openFhbpAdd()" text="新增复合编排"/>
                    <import-button @click="uploadHandler"/>
                </el-col>
                <el-col :span="12" style="display: flex;justify-content: flex-end;">
                    <right-toolbar
                            v-model:showSearch="showSearch"
                            @queryTable="handleQuery"
                    />
                </el-col>
            </el-row>
            <el-table v-loading="tableLoading" :data="tableData">
                <el-table-column label="序号" type="index" width="55" align="center"/>
                <el-table-column label="能力编码" prop="serviceCode" width="100" align="center"/>
                <el-table-column
                        label="能力名称"
                        prop="serviceName"
                        show-overflow-tooltip
                        min-width="100"
                />
                <el-table-column
                        label="所属分类"
                        prop="cateName"
                        show-overflow-tooltip
                        min-width="60"
                />
                <el-table-column label="能力类型" width="100" align="center">
                    <template #default="scope">
            <span>{{
                selectDictLabel(protocolTypeList, scope.row.serviceType)
                }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="能力方式" width="100" align="center">
                    <template #default="scope">
                        {{ handleServiceReleaseTypeText(scope.row.serverReleaseType) }}
                    </template>
                </el-table-column>
                <el-table-column
                        label="请求路径"
                        prop="mockUrl"
                        show-overflow-tooltip
                        width="180">
                    <template #default="scope">
                        <!-- 使用 el-tooltip 包裹显示悬停效果 -->
                        <!--            <el-tooltip content="" placement="top">-->
                        <span @click="copyText(scope.row.mockUrl)" style="cursor: pointer;">
              {{ scope.row.mockUrl }}
            </span>
                        <!--            </el-tooltip>-->
                    </template>
                </el-table-column>
                <el-table-column
                        label="主版本"
                        prop="serviceMasterVersion"
                        align="center"
                        width="60"
                >
                    <template #default="scope">
                        <span>{{ `V${scope.row.serviceMasterVersion}` }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        label="状态"
                        prop="serviceStatus"
                        align="center"
                        width="80"
                >
                    <template #default="scope">
                        <status-tag :status="scope.row.serviceStatus"/>
                    </template>
                </el-table-column>

                <el-table-column
                        label="编译状态"
                        prop="testPassStatus"
                        align="center"
                        width="80"
                >
                    <template #default="scope">
                       <span>
                           <span  v-if="scope.row.testPassStatus == '2' && scope.row.serviceStatus =='0'" @click="toViewTestPass(scope.row)" class="testPassStatusFail">异常</span>
                            <span class="testPassStatusSuccess" v-else>正常</span>

                       </span>

                    </template>
                </el-table-column>

                <el-table-column label="更新时间" prop="updateTime" width="160" align="center">
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="220"
                        class-name="small-padding fixed-width"
                >
                    <template #default="scope">
                        <text-release-button
                                v-if="
                scope.row.serviceStatus === '1' ||
                scope.row.serviceStatus === '2'
              "
                                :title="'是否确认发布' + scope.row.serviceName + '?'"
                                @click="handleAction('release', scope.row)"
                        />
                        <!-- <text-detail-button
                          @click="handleAction('test', scope.row)"
                          text="测试"
                        /> -->
                        <text-detail-button
                                v-if="
                scope.row.serviceStatus === '0' ||
                scope.row.serviceStatus === '2'
              "
                                @click="handleAction('version', scope.row)"
                                text="版本"
                        />
                        <text-edit-button
                                v-if="actionBtnHandler(scope.row.serviceStatus)"
                                @click="handleAction('edit', scope.row)"
                                text="修改"
                        />
                        <text-revoke-button
                                v-if="scope.row.serviceStatus === '0'"
                                text="撤销"
                                :title="'是否确认撤销' + scope.row.serviceName + '?'"
                                @click="handleAction('backout', scope.row)"
                        />
                        <!-- <text-release-button
                          v-if="scope.row.serviceStatus === '2'"
                          text="启动"
                          :title="'是否确认启动' + scope.row.serviceName + '?'"
                          @click="handleAction('start', scope.row)"
                        /> -->
                        <!-- <text-release-button
                          v-if="actionBtnHandler(scope.row.serviceStatus)"
                          text="提交审核"
                          :title="'是否确认提交审核' + scope.row.serviceName + '?'"
                          @click="handleAction('submit', scope.row)"
                        /> -->
                        <text-revoke-button
                                v-if="scope.row.serviceStatus === '2'"
                                text="作废"
                                :title="'是否确认作废' + scope.row.serviceName + '?'"
                                @click="handleAction('discard', scope.row)"
                        />
                        <text-delete-button
                                v-if="actionBtnHandler(scope.row.serviceStatus)"
                                :title="'是否确认删除' + scope.row.serviceName + '?'"
                                @click="handleAction('delete', scope.row)"
                        />

                        <el-dropdown @command="(command) => handleAction(command, scope.row)"
                                     class="ml10 el-button--text">
                            <div class="el-dropdown-link"
                                 style="font-size:12px;line-height: 27px;color: #409eff;margin-left:5px;">
                                更多
                                <el-icon class="el-icon-arrow-down el-icon--right">
                                    <ArrowDown/>
                                </el-icon>
                            </div>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="view" icon="el-icon-view">
                                        详情
                                    </el-dropdown-item>
                                    <el-dropdown-item command="export" icon="el-icon-download">
                                        导出
                                    </el-dropdown-item>
                                    <el-dropdown-item command="exportWSDL" icon="el-icon-download">
                                        下载WSDL文件
                                    </el-dropdown-item>
                                    <el-dropdown-item command="copy" icon="el-icon-copy-document"
                                                      v-hasPermi="['conn:capability:inventory:insert']">复制
                                    </el-dropdown-item>
                                    <!--
                                    <el-dropdown-item command="copy" icon="el-icon-copy-document" v-hasPermi="['conn:capability:inventory:insert']">
                                      复制
                                    </el-dropdown-item>
                                    -->
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>

                        <!--                        <el-dropdown @command="(command) => handleAction(command,scope.row)"-->
                        <!--                                     class="ml10 el-button&#45;&#45;text">-->
                        <!--              <span class="el-dropdown-link" style="font-size:12px;">-->
                        <!--                更多<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
                        <!--              </span>-->
                        <!--                            <el-dropdown-menu slot="dropdown">-->
                        <!--                                <el-dropdown-item command="view" icon="el-icon-view"-->
                        <!--                                                 >-->
                        <!--                                    详情-->
                        <!--                                </el-dropdown-item>-->
                        <!--                                &lt;!&ndash;                下载WSDL文件&ndash;&gt;-->
                        <!--                                <el-dropdown-item command="export" icon="el-icon-download"-->
                        <!--                                                  >导出-->
                        <!--                                </el-dropdown-item>-->
                        <!--                                <el-dropdown-item command="exportWSDL" icon="el-icon-download"-->
                        <!--                                                  >下载WSDL文件-->
                        <!--                                </el-dropdown-item>-->
                        <!--                                &lt;!&ndash;-->
                        <!--                                <el-dropdown-item command="copy" icon="el-icon-copy-document"-->
                        <!--                                                  v-hasPermi="['conn:capability:inventory:insert']">复制-->
                        <!--                                </el-dropdown-item>-->
                        <!--                                &ndash;&gt;-->
                        <!--                            </el-dropdown-menu>-->
                        <!--                        </el-dropdown>-->
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="handleQuery"
            />
        </div>
        <!-- 新增或编辑弹框 -->
        <el-dialog
                width="1200px"
                :title="dialogTitle"
                v-model="visible"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                @closed="handleClosed"

        >
            <choose-type v-if="steps.length === 0"/>
            <edit-container v-else/>
        </el-dialog>


        <!-- 版本升级或编辑弹框 -->
        <el-dialog
                width="1200px"
                :title="dialogTitle"
                v-model="versionVisible"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                @closed="handleVersionClosed"

        >
            <edit-container/>
        </el-dialog>
        <!-- 其他弹框弹框 view、test、submit、version -->
        <el-dialog
                width="1200px"
                :title="dialogTitle1"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                v-model="visible1"
                @closed="handleClosed"
        >
            <div class="view-container">

                <component
                        ref="upgradeRef"
                        :visible="visible1"
                        :is="dialogIs"
                        :row="curRowInfo"
                        :showNlbp="csfbInfo.serverReleaseType === '2'"
                        :showScript="csfbInfo.serverReleaseType === '5'"
                        @upgradeVersion="upgradeVersion"
                        @viewVersion="viewVersion"
                        @editVersion="editVersion"
                ></component>
                <dialog-footer
                        cancelText="关闭"
                        :showOk="false"
                        @cancel="visible1 = false"
                />
            </div>
        </el-dialog>
        <el-dialog
                width="1000px"
                title="能力版本详情"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                v-model="versionVisiblex"
        >
            <div class="view-container">
                <row-details
                        :showVersion="false"
                        v-model="versionVisiblex"

                        :showNlbp="csfbInfo.serverReleaseType === '2'"
                />
                <dialog-footer
                        cancelText="关闭"
                        :showOk="false"
                        @cancel="versionVisiblex = false"
                />
            </div>
        </el-dialog>

        <!-- 上传能力信息-->
        <el-dialog :title="upload.title" :close-on-click-modal="false" v-model="upload.open"
                   width="600px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".zip" :headers="upload.headers" :action="upload.url"
                       :disabled="upload.isUploading"
                       :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
                       drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <div class="el-upload__tip" style="color: red" slot="tip">
                    选择zip格式的压缩文件（通过其他环境导出的**-Service-Domain.zip压缩包）
                </div>
                <div class="el-upload__tip" style="color: red" slot="tip">
                    例：能力清单查询接口(S1000076)-Service-Domain.zip
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 新增或编辑复合编排 -->
        <el-dialog @close='closeFhbpDialog'
                   width="1200px"
                   :title="fbOptions.title"
                   v-model="fbOptions.isVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false">
            <step-fhbp
                    @updateFbOptions="updateFbOptions"
                    :fbOptions='fbOptions' @refresh="handleQuery"
                    v-if="fbOptions.operationType=='add' || fbOptions.operationType=='edit'|| fbOptions.operationType=='upgrade'"/>
            <div class="view-container" v-else-if="fbOptions.operationType=='view'">
                <step-fhbp-details :fbOptions='fbOptions'/>
                <dialog-footer
                        cancelText="关闭"
                        :showOk="false"
                        @cancel="closeFhbpDialog"
                />
            </div>
            <div class="view-container" v-else>
                <component
                        :visible="fbOptions.isVisible"
                        :is="fbOptions.componentList[fbOptions.operationType].is"
                        :fbOptions='fbOptions'
                        :formData='fbOptions.formData'
                        :showNlbp="true"
                        @upgradeVersion="upgradeVersion"
                        @viewVersion="viewVersion"
                        @editVersion="editVersion"
                ></component>
                <dialog-footer
                        cancelText="关闭"
                        :showOk="false"
                        @cancel="fbOptions.isVisible = false"
                />
            </div>

        </el-dialog>

        <el-dialog
            width="60%"
            title="日志内容"
            v-model="logDetailVisible"
            @close="hideMoreCsLog"
            :close-on-click-modal="false"
            :close-on-press-escape="false">
            <div class="log-detail" v-html="csLogParams.logContent">
            </div>
            <span slot="footer" class="dialog-footer" style="margin-top:20px;">
              <el-button type="primary" v-if="!csLogParams.end" @click="showMoreCsLog()">下一页</el-button>
              <el-button type="primary" class="m-l-10px" @click="hideMoreCsLog()">关闭</el-button>
            </span>
        </el-dialog>

        <!--    &lt;!&ndash; 未加载路由&ndash;&gt;-->
        <!--    <no-find-router v-if="noFindRouterVisible"  :visible.sync="noFindRouterVisible"/>-->

    </div>
</template>

<script>
import {
    searchServiceList,
    publishService,
    submitService,
    deleteService,
    revokeService,
    discardService,
    copyService, getCsfbData, reqHeaderSearch, resHeaderSearch,searchCsLog
} from "@slc/api/slc/inventory";
import {listApp} from "@slc/api/slc/categories";
import {statusOptions} from "./config/statusOptions";
import {debounceWrapper} from "@/utils/zmids";

import {serviceStore} from '@slc/store/service';
import {flowServiceStore} from '@slc/store/flowService';
import {mapActions, mapState} from 'pinia';

import {releaseArr, releaseTypeArr} from "./config/add";
import {handleServiceReleaseTypeText} from "./config/statusOptions";
import ChooseType from "./components/chooseType.vue";
import EditContainer from "./components/editContainer.vue";
import RowDetails from "./components/row-details.vue";
import RowVersion from "./components/row-version.vue";
import StepCsfb from "./components/step-csfb.vue";
import StatusTag from "./components/status-tag.vue";
import StepFhbp from "../orchestration/components/step-fhbp/index.vue";
import StepFhbpDetails from "../orchestration/components/step-fhbp/row-details.vue";
import StepFhbpVersion from "../orchestration/components/step-fhbp/row-version.vue";
import StepFhbpCsfb from "../orchestration/components/step-fhbp/step-csfb.vue";
import StepFhbpNotFindRoute from "../orchestration/components/step-fhbp/notFindRoute.vue";
import defaultSettings from '@/settings'
import { getToken } from '@/utils/auth';

import notFindRoute from "./components/notFindRoute.vue";
import {fbOptions as defaultFbOptions} from "../orchestration/config/fbDetail";

import {ElMessage as Message} from 'element-plus'

export default {
    name: "SlcInventory",
    components: {
        ChooseType,
        EditContainer,
        RowDetails,
        RowVersion,
        StepCsfb,
        StatusTag,
        notFindRoute,
        StepFhbp,
        StepFhbpDetails,
        StepFhbpVersion,
        StepFhbpCsfb,
        StepFhbpNotFindRoute
    },
    data() {
        return {
            logDetailVisible: false,
            csLogParams: {
                end: true,
                serviceVerId: '',
                fromLineNum: 1,
                lineNum: 1000,
            },
            fbOptions: {...defaultFbOptions},
            releaseTypeArr,
            releaseArr,
            showSearch: true,
            searchCateName: "",
            curClassifyIndex: 0,
            classifyList: [],
            cateLoaing: false,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                cateId: "",
                serviceNameLike: "",
                serviceCodeLike: "",
                serviceStatus: "",
                serviceType: "",
                serverReleaseType: "",
                mockUrlLike: "",
            },
            // 上传JSON参数
            upload: {
                // 是否显示弹出层（上传JSON参数）
                open: false,
                // 弹出层标题（上传JSON参数）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 设置上传的请求头部
                headers: { [defaultSettings.tokenName]: "Bearer " + getToken() },
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 上传的地址
                url: import.meta.env.VITE_APP_BASE_API + '/wf/manager/definition/upload',
                // 上传的ID（为空表示创建）
                ids: null,
            },
            tableData: [],
            total: 10,
            tableLoading: false,
            dialogTitle: "新增能力", // 新增/编辑弹框
            dialogTitle1: "", // 其他弹框弹框 view、test、submit、version
            dialogIs: "",
            visible1: false, // 其他弹框弹框显示
            versionVisiblex: false, // 版本详情
            curRowInfo: {}, // 点击查看版本，保存外层行数据
            statusOptions: Object.freeze(statusOptions),
            noFindRouterVisible: false,// 未加载路由详情
        };
    },
    created() {
        this.getClassifyList();
        this.handleQuery();
        // 获取数据字典：protocol_type
        this.getDicts("protocol_type").then((response) => {
            this.setProtocolTypeList(response.data || []);
            this.fbOptions.protocolTypeList = response.data || [];
        });
    },
    computed: {
        ...mapState(serviceStore, [
            "protocolTypeList",
            "dialogStatus",
            "dialogVersionStatus",
            "serverReleaseType",
            "visible",
            "steps",
            "csfbInfo",
            'versionVisible',
        ]),
        serverReleaseTypeInfo() {
            return releaseArr.find((n) => n.key === this.serverReleaseType) || {};
        },
    },
    watch: {
        serverReleaseType(val) {
            if (val) {
                const obj = releaseArr.find((n) => n.key === val)
                console.log(releaseArr);
                switch (this.dialogStatus) {
                    case 'add':
                        this.dialogTitle = `新增能力-${obj.title}`
                        break;
                    case 'edit':
                        this.dialogTitle = `编辑能力-${obj.title}`
                        break;
                    default:
                        break;
                }
            }
        }
    },
    methods: {
        ...mapActions(serviceStore, [
            'setSteps',
            "setProtocolTypeList",
            "setDialogStatus",
            "setDialogVersionStatus",
            "setServerReleaseType",
            "setServiceVerId",
            "setCurStep",
            "setMaxStep",
            "setVisible",
            "setVersionVisible",
            "setClassifyList",
            "doClear",
            "doVersionClear",
            "setChooseSjjInfo",
            "setChooseApiInfo",
            "setPzxxInfo",
            "setZhpzInfo",
            "setQqtInfo",
            "setInputData",
            "setOutputData",
            "chooseReleaseType",
            "getCsfbInfo",
            "getReqHeaderData",
            "getResHeaderData",
        ]),
        ...mapActions(flowServiceStore, ["doFlowClear"]),
        handleServiceReleaseTypeText,
        // 点击分类，更新右侧表格数据
        handleCateChange(n) {
            if (n.cateId === "all") {
                this.searchCateName = "";
                this.queryParams.cateId = "";
                this.getClassifyList();
            } else {
                this.queryParams.cateId = n.cateId;
            }
            this.handleQuery();
        },

        updateFbOptions(newFbOptions) {
            this.fbOptions = newFbOptions;
        },
        // 查询能力清单
        handleQuery: debounceWrapper(async function () {
            this.tableLoading = true;
            const res = await searchServiceList(this.queryParams);
            this.tableLoading = false;
            const {data = {}} = res;
            this.tableData = data.list || [];
            this.total = data.total || 0;
        }),
        // 查询分类列表
        getClassifyList: debounceWrapper(async function () {
            this.cateLoaing = true;
            const res = await listApp({cateName: this.searchCateName, cateNamespace: "anvil_capability_platform"});
            this.cateLoaing = false;
            const {code, data = []} = res;
            if (code === "200") {
                const obj = {
                    cateName: "所有分类",
                    cateId: "all",
                };
                this.classifyList = [obj, ...data];
                this.fbOptions.classifyList = data || [];

                this.setClassifyList(data);
                this.$nextTick(() => {
                    if (!this.searchCateName) {
                        this.$refs.cateTreeRef.setCurrentKey("all");
                    } else {
                        if (data && data.length > 0) {
                            this.$refs.cateTreeRef.setCurrentKey(data[0].cateId);
                            this.handleCateChange({cateId: data[0].cateId});
                        }
                    }
                });
            }
        }),
        // 重置查询
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 新增按钮
        handleAdd() {
            this.setDialogStatus('add')
            this.setVisible(true);
        },
        handleDetail() {
            this.noFindRouterVisible = true;


        },
        // 版本升级
        upgradeVersion(row) {
            if (row.isFlbp) {
                this.openFhbpEdit(row, 'upgrade');
            } else {
                this.handleVersionAction("upgrade", row);
            }
        },
        editVersion(row) {
            if (row.isFlbp) {
                this.openFhbpEdit(row, 'edit');
            } else {
                this.handleVersionAction("edit", row);
            }
        },
        async viewVersion(row) {
            if (row.isFlbp) {
                this.openFhbpView(row, 'view');
            } else {
                this.setDialogVersionStatus("view");
                await this.getCsfbInfo({serviceVerId: row.serviceVerId});
                this.handleViewData(row.serviceVerId)
                this.versionVisiblex = true;
            }

        },
        // copyText(text) {
        //   navigator.clipboard.writeText(text).then(() => {
        //     Message.success('复制成功');
        //   }).catch(() => {
        //     Message.error('复制失败');
        //   });
        // },
        copyText(text) {
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text)
                    .then(() => {
                        Message.success('复制成功');
                    })
                    .catch(() => {
                        // Message.error('复制失败');
                    });
            } else {
                // 使用回退方案
                this.fallbackCopyTextToClipboard(text);
            }
        },
        fallbackCopyTextToClipboard(text) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            try {
                document.execCommand('copy');
                Message.success('复制成功');
            } catch (err) {
                // Message.error('复制失败');
            }
            document.body.removeChild(textArea);
        },

        // 导出
        handleExport(row,) {
            this.downloadUrl(import.meta.env.VITE_APP_GATEWAY_URL + "/conn/service/exportService/" + row.serviceId);
            this.msgSuccess("正在启动导出......");
        },
        handleExportWSDL(row) {
            this.downloadUrl(import.meta.env.VITE_APP_GATEWAY_URL + "/conn/public/download/wsdl/" + row.wsdlContentId);
            this.msgSuccess("正在启动导出......");
        },
        async handleAction(key, row) {
            if (row) {
                this.setDialogStatus(key);
                this.curRowInfo = row;
                this.fbOptions.formData = row;
            }
            this.actionEvent(key, row);
        },
        handleVersionAction(key, row) {
            switch (key) {
                case 'upgrade':
                    this.dialogTitle = `升级能力版本-${this.serverReleaseTypeInfo.title}`
                    break;
                case 'edit':
                    this.dialogTitle = `编辑能力版本-${this.serverReleaseTypeInfo.title}`
                    break;
                default:
                    break;
            }

            this.setDialogVersionStatus(key);
            this.actionEvent(key, row);
        },
        async actionEvent(key, row) {
            const {serviceVerId} = row;
            if (key === "edit" || key === "upgrade") {
                if (row.serverReleaseType != '2') {
                    this.handleEdit(row);
                } else {
                    this.openFhbpEdit(row, key);
                }
            } else if (key === "notFindRoute") {
                console.log("notFindRoute", key)
                const obj = {
                    notFindRoute: {
                        title: "未加载路由详情",
                        is: "not-find-route",
                    }
                };
                this.dialogTitle1 = `${obj[key].title}`;
                this.dialogIs = obj[key].is;
                this.visible1 = true;
            } else if (
                key === "view" ||
                key === "test" ||
                key === "submit" ||
                key === "version"
            ) {

                if (row.serverReleaseType == '2') {
                    this.openFhbpView(row, key);
                    return
                }
                this.setServiceVerId(serviceVerId)
                this.setServerReleaseType(row.serverReleaseType);
                const obj = {
                    view: {
                        title: "能力接口详情",
                        is: "row-details",
                    },
                    test: {
                        title: "测试能力接口",
                        is: "step-csfb",
                    },
                    submit: {
                        title: "提交审核",
                        is: "step-csfb",
                    },
                    version: {
                        title: "查看能力版本",
                        is: "row-version",
                    },
                    notFindRoute: {
                        title: "未加载路由",
                        is: "not-find-route",
                    }
                };
                await this.getCsfbInfo({serviceVerId});
                this.handleViewData(serviceVerId)
                this.dialogTitle1 = `${obj[key].title}`;
                this.dialogIs = obj[key].is;
                this.visible1 = true;
            } else if (key === "release") {
                const res = await publishService({serviceVerId});
                if (res.code === "200") {
                    this.$message.success("发布成功！");
                    this.handleQuery();
                }
            } else if (key === "submit") {
                const res = await submitService({serviceVerId});
                if (res.code === "200") {
                    this.$message.success("提交审核成功！");
                    this.handleQuery();
                }
            } else if (key === "delete") {
                const res = await deleteService({id: row.serviceId});
                if (res.code === "200") {
                    this.$message.success("删除成功！");
                    this.handleQuery();
                }
            } else if (key === "backout") {
                const res = await revokeService({
                    serviceId: row.serviceId,
                    serviceVersion: row.serviceMasterVersion,
                });
                if (res.code === "200") {
                    this.$message.success("撤销成功！");
                    this.handleQuery();
                }
            } else if (key === "discard") {
                const res = await discardService({
                    serviceId: row.serviceId,
                    serviceVersion: row.serviceMasterVersion,
                });
                if (res.code === "200") {
                    this.$message.success("作废成功！");
                    this.handleQuery();
                }
            } else if (key === "export") {
                this.handleExport(row)
            } else if (key === "exportWSDL") {
                this.handleExportWSDL(row)
            } else if (key === "copy") {
                const res = await copyService({serviceId: row.serviceId});
                if (res.code === "200") {
                    this.$message.success("复制成功！");
                    this.handleQuery();
                }
            }
        },
        async handleEdit(row) {
            await this.getCsfbInfo({serviceVerId: row.serviceVerId});
            const {
                cateId,
                cateXpath = "/0",
                alarmSecs,
                retryTimes,
                jmsDatasourceCode,
                jmsType,
                jmsDestinationName,
                jmsRole,
                timeoutSecs,
                serviceName,
                servicePath,
                apiDomain,
                datasetDomain = {},
                protocolDomain,
                serviceDesc,
                limitCtrlStatus,
                limitCtrlParamval,
                limitCtrlType,
                httpRequestMethod,
                serviceType,
                serviceCode,
                mockUrl,
                serverReleaseType,
                inparamWithAttr,
                outparamWithAttr,
                permType,
            } = this.csfbInfo;
            this.setServiceVerId(row.serviceVerId)
            this.setServerReleaseType(serverReleaseType); // 当前注册方式key值
            this.chooseReleaseType(serverReleaseType); // 根据注册方式，给steps赋值
            console.log('serverReleaseType', serverReleaseType);
            if (this.dialogStatus === "edit" || this.dialogVersionStatus === "edit") {
                const pzxxIndex = this.steps.findIndex((n) => n.key === "PZXX");
                this.setCurStep(pzxxIndex);
                this.setMaxStep(pzxxIndex);
            }
            const {
                apiName,
                apiCode,
                apiDesc,
                apiType,
                wsOperation,
                apiVerId,
                apiVersion,
                apiId
            } = apiDomain || {};
            this.setChooseSjjInfo({...datasetDomain})
            this.setChooseApiInfo({
                apiName,
                apiId,
                apiCode,
                apiDesc,
                apiVerId,
                apiType,
                apiVersion,
                wsOperation,
            });
            let cateXpathArr = cateXpath.split("/");
            cateXpathArr.splice(0, 2);
            const cateIds = cateXpathArr.concat(cateId);
            this.setPzxxInfo({
                cateIds,
                serviceName,
                servicePath,
                serviceDesc,
                limitCtrlStatus: limitCtrlStatus === "0",
                limitCtrlParamval,
                limitCtrlType,
                serviceCode,
                serviceType,
                mockUrl,
                httpRequestMethod,
                timeoutSecs,
                alarmSecs,
                retryTimes,
                jmsDatasourceCode,
                jmsType,
                jmsDestinationName,
                jmsRole,
                permType,
            });
            const {
                isParamSerialize,
                isParamInSerialize,
                isParamOutSerialize,
                paramSerializeType,
                paramInSerializeType,
                paramOutSerializeType,
                paramInSerializeName,
                paramOutSerializeName,
                isHeaderInChange,
                isHeaderOutChange,
                isParamInChange,
                isParamOutChange,
            } = protocolDomain || {};
            this.setZhpzInfo({
                httpRequestMethod,
                serviceType,
                originApiType: apiType,
                paramSerializeType,
                paramInSerializeType,
                paramOutSerializeType,
                paramInSerializeName,
                paramOutSerializeName,
                isParamSerialize: isParamSerialize === "Y",
                isParamInSerialize: isParamInSerialize === "Y",
                isParamOutSerialize: isParamOutSerialize === "Y",
                isParamInChange: isParamInChange === "Y",
                isParamOutChange: isParamOutChange === "Y",
                inparamWithAttr: inparamWithAttr === "Y",
                outparamWithAttr: outparamWithAttr === "Y",
            });
            this.setQqtInfo({
                isHeaderInChange: isHeaderInChange === "Y",
                isHeaderOutChange: isHeaderOutChange === "Y",
            });

            console.log(this.visible)
            if (this.dialogStatus !== "version") {
                this.setVisible(true);
            } else {
                this.setVersionVisible(true);
            }
        },
        handleViewData(serviceVerId) {
            this.setServiceVerId(serviceVerId)
            this.getReqHeaderData({serviceVerId});
            this.getResHeaderData({serviceVerId});
            const {
                apiDomain = {},
                protocolDomain,
                inparamWithAttr,
                outparamWithAttr,
                connServiceParamInList,
                connServiceParamOutList,
            } = this.csfbInfo;
            const {
                isParamSerialize,
                isParamInSerialize,
                isParamOutSerialize,
                paramSerializeType,
                paramInSerializeType,
                paramOutSerializeType,
                paramInSerializeName,
                paramOutSerializeName,
                isHeaderInChange,
                isHeaderOutChange,
                isParamInChange,
                isParamOutChange,
            } = protocolDomain || {};
            this.setChooseApiInfo({...apiDomain})
            this.setZhpzInfo({
                paramSerializeType,
                paramInSerializeType,
                paramOutSerializeType,
                paramInSerializeName,
                paramOutSerializeName,
                isParamSerialize: isParamSerialize === "Y",
                isParamInSerialize: isParamInSerialize === "Y",
                isParamOutSerialize: isParamOutSerialize === "Y",
                isParamInChange: isParamInChange === "Y",
                isParamOutChange: isParamOutChange === "Y",
                inparamWithAttr: inparamWithAttr === "Y",
                outparamWithAttr: outparamWithAttr === "Y",
            });
            this.setQqtInfo({
                isHeaderInChange: isHeaderInChange === "Y",
                isHeaderOutChange: isHeaderOutChange === "Y",
            });
            this.setInputData(connServiceParamInList);
            this.setOutputData(connServiceParamOutList);
        },
        // 表格操作栏按钮显示控制
        actionBtnHandler(status) {
            // 驳回、暂存、作废
            const arr = ["1", "7", "9"];
            if (arr.includes(status)) {
                return true;
            }
            return false;
        },
        // 新增/编辑弹框关闭
        handleClosed() {
            this.handleQuery();
            // this.setVisible(false)
            // this.setVersionVisible(false)
            this.doClear();
            this.doFlowClear();
        },
        handleVersionClosed() {
            this.$refs.upgradeRef.getVersionList();
            this.doVersionClear();
        },
        // 导入按钮
        uploadHandler(row) {
            this.upload.title = "导入能力接口数据";
            this.upload.ids = (row && row.id) || 'create';
            this.upload.open = true;
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(response.msg, "上传结果", {dangerouslyUseHTMLString: true});
            this.handleQuery();
        },
        // 提交上传文件
        submitFileForm: debounceWrapper(function () {
            this.$refs.upload.submit();
        }),
        closeFhbpDialog() {
            if (this.fbOptions.versionTo) {
                delete this.fbOptions.versionTo;
                this.fbOptions.operationType = 'version';
                this.fbOptions.isVisible = true;
            } else {
                this.fbOptions.isVisible = false;
            }
        },
        openFhbpAdd() {
            let protocolTypeList = this.fbOptions.protocolTypeList;
            let classifyList = this.fbOptions.classifyList;
            this.fbOptions = {
                ...JSON.parse(JSON.stringify(defaultFbOptions)),
                protocolTypeList,
                classifyList,
                isVisible: true,
                operationType: 'add',
                title: '新增能力-复合编排'
            };

        },
        async openFhbpEdit(row, key) {
            const res = await getCsfbData({serviceVerId: row.serviceVerId});
            const {data = {cateXpath: "/0"}} = res;
            const {connServiceParamInList = []} = data;
            let cateXpathArr = data.cateXpath.split("/");
            cateXpathArr.splice(0, 2);
            const cateIds = cateXpathArr.concat(data.cateId);
            let formData = {...this.fbOptions.formData, ...data, serviceVerId: row.serviceVerId, cateIds};
            let csfbTableData = connServiceParamInList;
            this.fbOptions = {
                ...this.fbOptions,
                versionTo: row.isFlbp,
                formData,
                csfbTableData,
                isVisible: true,
                curStep: 0,
                operationType: key,
                title: key == 'edit' ? '编辑能力-复合编排' : '升级能力-复合编排',
            };
        },
        openFhbpView(row, key) {
            let getCsfb = () => {
                return new Promise(resolve => {
                    getCsfbData({serviceVerId: row.serviceVerId}).then(
                        response => {
                            if (response) {
                                resolve(response)
                            }
                        }
                    );
                });
            }
            let getReqHeaderData = () => {
                return new Promise(resolve => {
                    reqHeaderSearch({serviceVerId: row.serviceVerId}).then(
                        response => {
                            if (response.data) {
                                console.log(response.data)
                                resolve(response.data)
                            }
                        }
                    );
                });
            }
            let getResHeaderData = () => {
                return new Promise(resolve => {
                    resHeaderSearch({serviceVerId: row.serviceVerId}).then(
                        response => {
                            if (response.data) {
                                resolve(response.data)
                            }
                        }
                    );
                });
            }
            Promise.all([getCsfb(), getReqHeaderData(), getResHeaderData()]).then((item) => {
                console.log(item)
                const res = item[0];
                const {data = {cateXpath: "/0"}} = res;
                const {connServiceParamInList = []} = data;
                let cateXpathArr = data.cateXpath.split("/");
                cateXpathArr.splice(0, 2);
                const cateIds = cateXpathArr.concat(data.cateId);
                let formData = {
                    ...this.fbOptions.formData,
                    ...data,
                    serviceVerId: row.serviceVerId,
                    reqHeaderList: item[1],
                    resHeaderList: item[2],
                    cateIds
                };
                let csfbTableData = connServiceParamInList;
                this.fbOptions = {
                    ...this.fbOptions,
                    versionTo: row.isFlbp,
                    formData,
                    csfbTableData,
                    isVisible: true,
                    curStep: 0,
                    inputData: data.connServiceParamInList,
                    outputData: data.connServiceParamOutList,
                    operationType: key,
                    title: this.fbOptions.componentList[key].title,
                };
            })
        },
        toViewTestPass({serviceVerId}) {
            this.csLogParams = {
                serviceVerId: serviceVerId,
                fromLineNum: 1,
                lineNum: 1000,
            }
            searchCsLog(this.csLogParams).then(res => {
                if (res) {
                    const {data} = res;
                    this.csLogParams.logContent = data.logContent || '无相关日志';
                    this.csLogParams.end = data.end;
                    this.logDetailVisible = true;

                }

            })
        },
        hideMoreCsLog() {
            this.logDetailVisible = false;
        },
        showMoreCsLog() {
            searchCsLog(this.csLogParams).then(res => {
                if (res) {
                    const {data} = res;
                    this.csLogParams.logContent += data.logContent;
                    this.csLogParams.fromLineNum =  data.toLineNum;
                    this.csLogParams.end = data.end;
                }

            })

        },
    },
};
</script>

<style lang="scss" scoped>
$border: 1px solid rgba(220, 223, 230, 1);
.inventory-container {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 10px;

  .view-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .left {
    width: 20%;
    height: 100%;

    .title {
      width: 100%;
      height: 60px;
      background-color: rgb(235, 237, 240);
      line-height: 60px;
      color: #000;
      font-size: 18px;
      padding-left: 10px;
    }

    .content {
      width: 100%;
      height: 100%;
      border: $border;
      padding: 10px;
      box-sizing: border-box;
      overflow: auto;

      .conetnt-box {
        width: 100%;
        padding-top: 10px;
        overflow-y: auto;
      }
    }
  }

  .right {
    height: 100%;
    width: calc(80% - 10px);
    border: $border;
    padding: 10px 10px 30px;
    overflow: auto;

    .add {
      margin-bottom: 22px;
    }
  }

  :deep( .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content) {
    // 设置颜色
    background-color: rgba(
                    135,
                    206,
                    235,
                    0.2
    ); // 透明度为0.2的skyblue，作者比较喜欢的颜色
    color: #409eff; // 节点的字体颜色
    font-weight: bold; // 字体加粗
  }

  .testPassStatusSuccess {
    color: var(--el-color-primary);
    cursor: pointer;
  }

  .testPassStatusFail {
    color: var(--el-color-danger);
    cursor: pointer;

    &:hover {
      color: #888;
    }

  }

    .log-detail {
        // height: calc(100%-80px);
        overflow: auto;
        white-space: pre-wrap;
        height: 600px;
        margin-bottom: 10px;
    }

}
</style>
